/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package persistence;

import entityBeans.Collectioncode;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entityBeans.Recordlevelelement;
import java.util.ArrayList;
import java.util.List;
import persistence.exceptions.IllegalOrphanException;
import persistence.exceptions.NonexistentEntityException;

/**
 *
 * @author allankv
 */
public class CollectioncodeJpaController {

    public CollectioncodeJpaController() {
        emf = Persistence.createEntityManagerFactory("bdd-javaPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }
    /*
     * > Criar metodo
     * -Procuro registro
     * -Se nao existe: Salva e retorna instancia com ID
     * -Se existe: retorna instancia encontrada
     */
    public Collectioncode save(Collectioncode collectioncode) {
        Collectioncode aux = findCollectioncode(collectioncode.getCollectioncode());
        if(aux==null)
            return create(collectioncode);
        else
            return aux;
    }
    
    public Collectioncode create(Collectioncode collectioncode) {
        // Entidade a ser retornada
        Collectioncode r = null;
        if (collectioncode.getRecordlevelelementList() == null) {
            collectioncode.setRecordlevelelementList(new ArrayList<Recordlevelelement>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Recordlevelelement> attachedRecordlevelelementList = new ArrayList<Recordlevelelement>();
            for (Recordlevelelement recordlevelelementListRecordlevelelementToAttach : collectioncode.getRecordlevelelementList()) {
                recordlevelelementListRecordlevelelementToAttach = em.getReference(recordlevelelementListRecordlevelelementToAttach.getClass(), recordlevelelementListRecordlevelelementToAttach.getIdrecordlevelelement());
                attachedRecordlevelelementList.add(recordlevelelementListRecordlevelelementToAttach);
            }
            collectioncode.setRecordlevelelementList(attachedRecordlevelelementList);
            // Merge salva e retorna instancia salva
            r = em.merge(collectioncode);
            for (Recordlevelelement recordlevelelementListRecordlevelelement : collectioncode.getRecordlevelelementList()) {
                Collectioncode oldCollectioncodeOfRecordlevelelementListRecordlevelelement = recordlevelelementListRecordlevelelement.getCollectioncode();
                recordlevelelementListRecordlevelelement.setCollectioncode(collectioncode);
                recordlevelelementListRecordlevelelement = em.merge(recordlevelelementListRecordlevelelement);
                if (oldCollectioncodeOfRecordlevelelementListRecordlevelelement != null) {
                    oldCollectioncodeOfRecordlevelelementListRecordlevelelement.getRecordlevelelementList().remove(recordlevelelementListRecordlevelelement);
                    oldCollectioncodeOfRecordlevelelementListRecordlevelelement = em.merge(oldCollectioncodeOfRecordlevelelementListRecordlevelelement);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
        return r;
    }

    public void edit(Collectioncode collectioncode) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Collectioncode persistentCollectioncode = em.find(Collectioncode.class, collectioncode.getIdcollectioncode());
            List<Recordlevelelement> recordlevelelementListOld = persistentCollectioncode.getRecordlevelelementList();
            List<Recordlevelelement> recordlevelelementListNew = collectioncode.getRecordlevelelementList();
            List<String> illegalOrphanMessages = null;
            for (Recordlevelelement recordlevelelementListOldRecordlevelelement : recordlevelelementListOld) {
                if (!recordlevelelementListNew.contains(recordlevelelementListOldRecordlevelelement)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Recordlevelelement " + recordlevelelementListOldRecordlevelelement + " since its collectioncode field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<Recordlevelelement> attachedRecordlevelelementListNew = new ArrayList<Recordlevelelement>();
            for (Recordlevelelement recordlevelelementListNewRecordlevelelementToAttach : recordlevelelementListNew) {
                recordlevelelementListNewRecordlevelelementToAttach = em.getReference(recordlevelelementListNewRecordlevelelementToAttach.getClass(), recordlevelelementListNewRecordlevelelementToAttach.getIdrecordlevelelement());
                attachedRecordlevelelementListNew.add(recordlevelelementListNewRecordlevelelementToAttach);
            }
            recordlevelelementListNew = attachedRecordlevelelementListNew;
            collectioncode.setRecordlevelelementList(recordlevelelementListNew);
            collectioncode = em.merge(collectioncode);
            for (Recordlevelelement recordlevelelementListNewRecordlevelelement : recordlevelelementListNew) {
                if (!recordlevelelementListOld.contains(recordlevelelementListNewRecordlevelelement)) {
                    Collectioncode oldCollectioncodeOfRecordlevelelementListNewRecordlevelelement = recordlevelelementListNewRecordlevelelement.getCollectioncode();
                    recordlevelelementListNewRecordlevelelement.setCollectioncode(collectioncode);
                    recordlevelelementListNewRecordlevelelement = em.merge(recordlevelelementListNewRecordlevelelement);
                    if (oldCollectioncodeOfRecordlevelelementListNewRecordlevelelement != null && !oldCollectioncodeOfRecordlevelelementListNewRecordlevelelement.equals(collectioncode)) {
                        oldCollectioncodeOfRecordlevelelementListNewRecordlevelelement.getRecordlevelelementList().remove(recordlevelelementListNewRecordlevelelement);
                        oldCollectioncodeOfRecordlevelelementListNewRecordlevelelement = em.merge(oldCollectioncodeOfRecordlevelelementListNewRecordlevelelement);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = collectioncode.getIdcollectioncode();
                if (findCollectioncode(id) == null) {
                    throw new NonexistentEntityException("The collectioncode with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Collectioncode collectioncode;
            try {
                collectioncode = em.getReference(Collectioncode.class, id);
                collectioncode.getIdcollectioncode();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The collectioncode with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Recordlevelelement> recordlevelelementListOrphanCheck = collectioncode.getRecordlevelelementList();
            for (Recordlevelelement recordlevelelementListOrphanCheckRecordlevelelement : recordlevelelementListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Collectioncode (" + collectioncode + ") cannot be destroyed since the Recordlevelelement " + recordlevelelementListOrphanCheckRecordlevelelement + " in its recordlevelelementList field has a non-nullable collectioncode field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(collectioncode);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Collectioncode> findCollectioncodeEntities() {
        return findCollectioncodeEntities(true, -1, -1);
    }

    public List<Collectioncode> findCollectioncodeEntities(int maxResults, int firstResult) {
        return findCollectioncodeEntities(false, maxResults, firstResult);
    }

    private List<Collectioncode> findCollectioncodeEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Collectioncode.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }
    /*
     * > Criar metodo
     * Consulta no banco a partir de um SQL pre definido
     * Consulta por collection code
     */
    public Collectioncode findCollectioncode(String q) {
        Query query= getEntityManager().createNamedQuery("Collectioncode.findByCollectioncode");
        query.setParameter("collectioncode",q);

        return query.getResultList().isEmpty()?null:(Collectioncode)query.getResultList().get(0);
    }
    public Collectioncode findCollectioncode(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Collectioncode.class, id);
        } finally {
            em.close();
        }
    }

    public int getCollectioncodeCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Collectioncode> rt = cq.from(Collectioncode.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
